package java_thinking.unit_21._21_15;

import net.jcip.annotations.ThreadSafe;

import java.util.Random;
import java.util.concurrent.locks.*;

/**
 * @Desc:   15-4 基于 ReentrantLock 实现的随机数生成器
 * @author: cww
 * @DateTime: 2019-06-28 23:30
 */
@ThreadSafe
public class ReentrantLockPseudoRandom  extends Random {
    private final ReentrantLock lock = new ReentrantLock(false);
    private int seed;

    public ReentrantLockPseudoRandom(int seed) {
        this.seed = seed;
    }

    public int getSeed() {
        return seed;
    }

    public int nextSeed(int n) {
        lock.lock();
        try {
            int old = seed;
            seed = nextInt(old);
            int remainder = old % n;
            return remainder > 0 ? remainder : remainder + n;
        } finally {
            lock.unlock();
        }
    }
}
